import {Component, Input, OnInit} from "@angular/core";
import {NzDrawerRef, NzMessageService} from "ng-zorro-antd";
import {HttpClient} from "@angular/common/http";
import {I18NService} from "@core/i18n/i18n.service";
import { saveAs } from 'file-saver';
import {FormGroup, Validators} from "@angular/forms";
import {BaseComponent} from "@shared/base/base.component";
@Component({
  selector: 'nz-drawer-custom-component',
  template: `
    <div>
          <label  nzRequired  maxlength="50">试卷标题</label>{{errorMessage}}
          <input nz-input  [(ngModel)]="paperName">

          <label   maxlength="200" >试卷描述</label>
          <textarea rows="3" nz-input  [(ngModel)]="describe"></textarea>
      
      <button nzType="primary" (click)="close()" nz-button>提交</button>
    </div>
  `
})
export class NzDrawerCustomComponent{
  @Input() idStr = '';
  paperName:'';
  describe:'';
  errorMessage:string;
  validateForm: FormGroup;
  constructor(
    private drawerRef: NzDrawerRef<string>,
    private http: HttpClient,
    private message: NzMessageService,
    private i18nService: I18NService,
    ) {}

  close(): void {
    if (this.paperName!=''&&this.paperName!=undefined&&this.paperName!=null&&this.idStr!=undefined&&this.idStr!=null) {
      this.exportQuestionByIds(this.describe, this.idStr, this.paperName);
    }else {
      if(this.idStr!=undefined||this.idStr!=null){
        this.errorMessage='未选择试题';
      } else {
        this.errorMessage='试卷名不能为空';
      }
    }


    // this.drawerRef.close(this.idStr);
  }
  private getDisposition(data: string) {
    const arr: any = (data || '')
      .split(';')
      .filter(i => i.includes('='))
      .map(v => {
        const strArr = v.split('=');
        const utfId = `UTF-8''`;
        let value = strArr[1];
        if (value.startsWith(utfId)) {
          value = value.substr(utfId.length);
        }
        return { [strArr[0].trim()]: value };
      });
    return arr.reduce((o, item: any) => item, {});
  }
  exportQuestionByIds(describe:string,idStr:string,paperName:string):void {
    this.http.get( '/get/web/download/questionModule/QuestionService/exportQuestionByIds', {responseType:'blob',observe:'response',params:{describe:describe,idStr:idStr,paperName:paperName}})
      .subscribe(res => {
        if (res.status !== 200 || res.body.size <= 0) {
          this.message.error(this.i18nService.translate('导出失败'));
          return;
        }
        const name=res.headers.get('Content-disposition');
        const disposition: any = this.getDisposition(name);
        const fileName =
          disposition[`filename*`] ||
          disposition[`filename`] ||
          res.headers.get('filename') ||
          res.headers.get('x-filename');
        saveAs(res.body, decodeURI(fileName));
        this.message.success(this.i18nService.translate('导出成功'));
      }, err => {
        this.message.error(this.i18nService.translate('导出失败'));
      });
  }
}
